import os
import sys
import logging
from datetime import datetime
from pathlib import Path

# 设置项目根目录和后端目录
BASE_DIR = Path(__file__).parent.parent  # 指向 backend 目录
sys.path.append(str(BASE_DIR))  # 添加 backend 目录到 Python 路径

# 设置日志
def setup_logging():
    log_dir = BASE_DIR / 'logs'
    log_dir.mkdir(exist_ok=True)
    
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(
                log_dir / f'backend_{datetime.now().strftime("%Y%m%d")}.log',
                encoding='utf-8'
            ),
            logging.StreamHandler()
        ]
    )
    return logging.getLogger(__name__)

def init_database():
    logger.info("初始化数据库...")
    try:
        from scripts.init_db import init_database
        init_database()
        logger.info("数据库初始化成功")
    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        sys.exit(1)

def start_server():
    logger.info("启动后端服务器...")
    try:
        import uvicorn
        from app.main import app  # 直接从 app 导入
        uvicorn.run(
            app,
            host="127.0.0.1",
            port=8000,
            log_level="info"
        )
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    logger = setup_logging()
    
    import argparse
    parser = argparse.ArgumentParser(description='后端服务器管理')
    parser.add_argument('--init-db', action='store_true', help='初始化数据库')
    args = parser.parse_args()

    if args.init_db:
        init_database()
    
    start_server() 